package com.llap.exp190929.service;

import com.llap.exp190929.entity.CardAccount;
import com.llap.exp190929.repository.CardAccountRepository;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@AllArgsConstructor
@Slf4j
public class CardAccountService {
    private CardAccountRepository cardAccountRepository;

    public CardAccount findCardAccount(String cardNo, String password) {
        return cardAccountRepository.findByCardNoAndPassword(cardNo, password);
    }

    public CardAccount findCardAccount(String cardNo) {
        return cardAccountRepository.findByCardNo(cardNo);
    }

    public Page<CardAccount> findCardAccounts(int page, int pageSize) {
        return cardAccountRepository.findAll(PageRequest.of(page - 1, pageSize));
    }

    @Transactional
    public CardAccount addCardAccount(CardAccount account) {
        if (account.getCardNo() == null || cardAccountRepository.findByCardNo(account.getCardNo()) != null) return null;
        return cardAccountRepository.save(account);
    }

    @Transactional
    public CardAccount updateCardAccount(CardAccount account) {
        if (account.getCardNo() == null) return null;
        CardAccount original = cardAccountRepository.findByCardNo(account.getCardNo());
        if (original == null) return null;
        if (account.getPassword() == null || account.getPassword().isEmpty()) return null;
        if (!account.getPassword().matches("^\\d{6}$")) return null;
        original.setPassword(account.getPassword());
        return cardAccountRepository.save(original);
    }

    @Transactional
    public void deleteCardAccount(String cardNo) {
        cardAccountRepository.deleteByCardNo(cardNo);
    }
}
